<template>
  <div class="wrap">
    <div class="shipment-type-box" v-if="shipmentTypeList.length > 1">
      <el-radio-group class="platform-radio" v-model="queryParams.shipmentType" size="small" @change="changeShipmentType" :disabled="loading">
        <el-radio-button
          v-for="item in shipmentTypeList"
          :key="item.type"
          :label="item.type"
        >
          {{item.text}}
        </el-radio-button>
      </el-radio-group>
    </div>
    <user-check-box v-model="queryParams.userIds" @change="changeOption" :filter-stop="true" @apiUserFinish="changeOption" :disdisabled="loading"></user-check-box>

    <div class="header mgt20">
      <div class="left">
        <el-select v-model="queryParams.transferType" placeholder="请选择运输类型" size="small" class="mgr10" @change="changeOption">
          <el-option label="运输类型" value=""></el-option>
          <el-option
            v-for="item in transferTypeList"
            :key="item.transferType"
            :label="item.typeName"
            :value="item.transferType">
          </el-option>
        </el-select>

        <el-select v-model="queryParams.labelStatus" placeholder="请选择仓库类型" size="small" class="mgr10" @change="changeOption">
          <el-option :label="$t('table.贴标状态')" value=""></el-option>
          <el-option :label="$t('shipment.无需贴标')" :value="-1"></el-option>
          <el-option :label="$t('labelOrder.待贴标')" :value="1"></el-option>
          <el-option :label="$t('labelOrder.已贴标')" :value="2"></el-option>
        </el-select>

        <el-select v-model="queryParams.BGMethod" size="small" class="mgl10" @change="changeOption">
          <el-option label="报关方式" value=""></el-option>
          <el-option v-for="item in allBGMethodList" :key="item" :value="item" :label="getShipmentBGMethodStr(item)"></el-option>
        </el-select>

        <div class="mgt10 batch-box">
          <el-input
            type="textarea"
            :autosize="{minRows: 3}"
            placeholder="批量搜索：请输入货件单号/发货计划/SKU（一行一个）"
            v-model="queryParams.keyword"
          >
          </el-input>
          <el-button class="batch-btn" type="primary" @click="changeOption">搜索</el-button>
        </div>

      </div>
      <div class="right" v-if="false">
        <el-input
          size="small"
          style="width: 250px; margin-right: 10px; margin-bottom: 10px"
          v-model="queryParams.keyword"
          :placeholder="$t('搜索货件单号')"
          @keyup.enter.native="changeOption"
          clearable
          @clear="changeOption"
        ></el-input>
        <el-button size="small" type="primary" @click="changeOption">{{ $t('common.search') }}</el-button>
      </div>
    </div>
    <div>
      <el-tabs v-model="queryParams.status2" @tab-click="changeOption">
        <el-tab-pane
          v-for="item in shipmentStatusList"
          :key="item.status"
          :label="`${item.text}(${item.num})`"
          :name="item.status"
        ></el-tab-pane>
      </el-tabs>
    </div>
    <div class="content">
      <el-table
        :data="data"
        border
        v-loading="loading"
        v-tableHeight="{bottomOffset: 50}"
        height="100px"
        ref="tableData"
      >
        <el-table-column
          :label="$t('table.shipmentNumber')"
          prop="shipmentNo"
          align="center"
          min-width="250"
          show-overflow-tooltip
          fixed="left"
        >
          <template slot-scope="{row}">
            <diy-link @click="jumpInfo(row)">{{row.shipmentNo}}</diy-link>
          </template>
        </el-table-column>
        <el-table-column
          label="发货计划"
          prop="shippingPlanNo"
          align="center"
          min-width="250"
        >
          <template v-slot="{row}">
            <diy-link @click="jumpPageNewTag('shippingPlanInfo',{id: row.planId})">{{row.shippingPlanNo}}</diy-link>
          </template>
        </el-table-column>
        <el-table-column
          label="用户"
          prop="userAccount"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          label="运输类型"
          prop="transferType"
          align="center"
          min-width="150"
        >
          <template v-slot="{row}">
            {{getTransferName(row.transferType)}}
          </template>
        </el-table-column>
        <el-table-column
          label="箱子数量"
          prop="exBoxNum"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <num2 :right-num="row.exBoxNum" :left-num="getRlBoxNum(row)"></num2>
          </template>
        </el-table-column>
        <el-table-column
          label="SKU种数"
          prop="exSkuNum"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <template v-if="row.status2 === FINISHED_SHELVES()">
              <num2 :right-num="row.exSkuNum" :left-num="row.rlSkuNum"></num2>
            </template>
            <template v-else>
              {{row.exSkuNum}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="商品数量"
          prop="exSkuNum"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <template v-if="row.status2 === FINISHED_SHELVES()">
              <num2 :right-num="row.exGoodsNum" :left-num="row.rlGoodsNum"></num2>
            </template>
            <template v-else>
              {{row.exGoodsNum}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="实重（kg）"
          prop="sumWeight"
          align="center"
          min-width="150"
        ></el-table-column>
        <el-table-column
          label="方数"
          prop="sumSquareNumber"
          align="center"
          min-width="100"
        ></el-table-column>
        <el-table-column
          label="计费重"
          prop="sumCalWeight"
          align="center"
          min-width="100"
        ></el-table-column>

        <el-table-column
          label="报关方式"
          prop="BGMethod"
          min-width="100"
          align="center"
        >
          <template v-slot="{row}">
            {{getShipmentBGMethodStr(row.BGMethod) || '-'}}
          </template>
        </el-table-column>
        <el-table-column
          label="货件类型"
          prop="shipmentType"
          min-width="100"
          align="center"
        >
          <template v-slot="{row}">
            {{getShipmentTypeStr2(row.shipmentType) || '-'}}
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('table.贴标状态')"
          prop="labelStatus"
          align="center"
          min-width="150"
        >
          <template v-slot="{row}">
            {{row.labelOrder ? getLabelStatusStr(row.labelOrder.status) : '-'}}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.createTime2')"
          prop="createTime"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column
          label="预计送达时间"
          prop="estimateTime"
          align="center"
          width="150"
        >
          <template v-slot="{row}">
            {{row.estimateTime || '-'}}
          </template>
        </el-table-column>
        <el-table-column
          label="上架时间"
          prop="confirmTime"
          align="center"
          width="180"
        >
          <template v-slot="{row}">
            {{row.confirmTime || '-'}}
          </template>
        </el-table-column>

        <el-table-column
          label="货件状态"
          prop="status2"
          align="center"
          min-width="150"
        >
          <template v-slot="{row}">
            {{getShipmentStatus2Str(row.status2)}}
          </template>
        </el-table-column>


        <el-table-column
          :label="$t('table.operate')"
          prop="操作"
          align="left"
          min-width="250"
          fixed="right"
        >
          <template slot-scope="{row}">
            <el-button @click="jumpInfo(row)" type="view">{{$t('common.view')}}</el-button>
            <export-shipment-a4 :shipment="row" v-if="false"></export-shipment-a4>
            <export-shipment-template :shipment="row" style="display: inline-block" class="mgl10 mgr10"></export-shipment-template>
            <label-order-button :id="row.labelOrder.id" v-if="row.labelOrder"></label-order-button>
            <combination-order-button :id="row.combinationOrder.id" v-if="row.combinationOrder"></combination-order-button>
            <del-shipment-button :id="row.id" :data="row" @changeRow="getData"></del-shipment-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-wrap">
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </div>

  </div>
</template>

<script>
import UserCheckBox from "@/views/shipment/components/UserCheckBox.vue";
import {delShipment} from "@/api/shipment";
import {getShipmentList} from "@/api/shipmentV2"
import {getWareHouseName, isMiddleRole, isOneShippingRole} from "@/utils/common";
import {getFalabellaName, getMercadoName, getShopeeName} from "@/utils";
import LabelOrderButton from "@/views/shipment/components/LabelOrderButton.vue";
import {
  ABOLISHED,
  FINISHED_SHELVES,
  FINISHED_SORTING,
  getShipmentBGMethodStr,
  getShipmentStatus2Str,
  getShipmentStatusStr,
  getShipmentTypeStr,
  getShipmentTypeStr2,
  HALF_SHELVES,
  OFFICIAL_DELIVERED,
  OFFLINE_DELIVERED,
  WAIT_CONFIRM,
  WAIT_CUSTOMS_CLEARANCE,
  WAIT_CUSTOMS_DECLARATION,
  WAIT_FL_RECEIVE,
  WAIT_MAKE_CABINET,
  WAIT_RECEIVE,
  WAIT_SHIPMENT,
  WAIT_SORTING
} from "@/utils/shipment";
import {getLabelStatusStr} from "@/utils/labelOrder";
import ToolTipShipmentBox from "@/views/shipment/components/ToolTipShipmentBox.vue";
import ExportShipmentA4 from "@/views/shipment/components/ExportShipmentA4.vue";
import {jumpCombinationInfo, jumpPageNewTag} from "@/utils/jumpView";
import shippingPlanDataMixin from "@/views/shippingPlan/mixin/shippingPlanDataMixin";
import {PLAN_TYPE_FL, PLAN_TYPE_MW} from "@/utils/shippingPlan";
import checkPermission from "@/utils/permission";
import {ROLE_FIRST_LEG} from "@/utils/admin";
import ExportShipmentTemplate from "@/views/shipment/components/ExportShipmentTemplate.vue";
import CombinationOrderButton from "@/views/shipment/components/CombinationOrderButton.vue";
import Num2 from "@/components/Common/Num2.vue";
import BGMethodMixin from "@/views/shipment/mixin/BGMethodMixin";
import DLShipmentBoxBtn from "@/views/shipment/components/DLShipmentBoxBtn.vue";
import DelShipmentButton from "@/views/shipment/components/DelShipmentButton.vue";

export default {
  name: "shipmentListFirstLeg",
  components: {
    DelShipmentButton,
    Num2, CombinationOrderButton, ExportShipmentTemplate, ExportShipmentA4, LabelOrderButton, UserCheckBox},
  mixins: [shippingPlanDataMixin, BGMethodMixin],
  computed: {
    shipmentStatusList(){
      let shipmentStatusList = [
        {status: WAIT_FL_RECEIVE, text: getShipmentStatus2Str(WAIT_FL_RECEIVE), num: 0},
        {status: WAIT_MAKE_CABINET, text: getShipmentStatus2Str(WAIT_MAKE_CABINET), num: 0},
        {status: WAIT_CUSTOMS_DECLARATION, text: getShipmentStatus2Str(WAIT_CUSTOMS_DECLARATION), num: 0},
        {status: WAIT_SHIPMENT, text: getShipmentStatus2Str(WAIT_SHIPMENT), num: 0},
        {status: WAIT_CUSTOMS_CLEARANCE, text: getShipmentStatus2Str(WAIT_CUSTOMS_CLEARANCE), num: 0},
        {status: 'fl_finished', text: '已完成', num: 0}, // 头程的已完成
        {status: 'all', text: '全部', num: 0}, // 全部
      ];
      const routeName = this.$route.name
      // 头程
      if(routeName === 'shipmentListFirstLeg'){
        // 如果不是头程
        if(!checkPermission(ROLE_FIRST_LEG)){
          shipmentStatusList = [
            {status: 'fl_transit', text: '运输中', num: 0},
            {status: WAIT_RECEIVE, text: getShipmentStatus2Str(WAIT_RECEIVE), num: 0},
            {status: WAIT_SORTING, text: getShipmentStatus2Str(WAIT_SORTING), num: 0},
            {status: FINISHED_SORTING, text: getShipmentStatus2Str(FINISHED_SORTING), num: 0},
            {status: HALF_SHELVES, text: getShipmentStatus2Str(HALF_SHELVES), num: 0},
            {status: FINISHED_SHELVES, text: getShipmentStatus2Str(FINISHED_SHELVES), num: 0},
            {status: 'all', text: '全部', num: 0}, // 全部
          ]
          if(this.queryParams.shipmentType === 'mkd_full' || this.queryParams.shipmentType === 'mkd_cbt_full'){
            shipmentStatusList = [
              {status: 'fl_transit', text: '运输中', num: 0},
              {status: WAIT_RECEIVE, text: getShipmentStatus2Str(WAIT_RECEIVE), num: 0},
              {status: WAIT_SORTING, text: getShipmentStatus2Str(WAIT_SORTING), num: 0},
              {status: FINISHED_SORTING, text: getShipmentStatus2Str(FINISHED_SORTING), num: 0},
              {status: OFFICIAL_DELIVERED, text: getShipmentStatus2Str(OFFICIAL_DELIVERED), num: 0},
              {status: ABOLISHED, text: getShipmentStatus2Str(ABOLISHED), num: 0},
              {status: 'all', text: '全部', num: 0}, // 全部
            ]
          }
          if(this.queryParams.shipmentType === 'offline_delivery'){
            shipmentStatusList = [
              {status: 'fl_transit', text: '运输中', num: 0},
              {status: WAIT_RECEIVE, text: getShipmentStatus2Str(WAIT_RECEIVE), num: 0},
              {status: WAIT_SORTING, text: getShipmentStatus2Str(WAIT_SORTING), num: 0},
              {status: FINISHED_SORTING, text: getShipmentStatus2Str(FINISHED_SORTING), num: 0},
              {status: OFFLINE_DELIVERED, text: getShipmentStatus2Str(OFFLINE_DELIVERED), num: 0},
              {status: 'all', text: '全部', num: 0}, // 全部
            ]
          }
        }
      }
      // 移仓
      if(routeName === 'shipmentListMoveWarehouse'){
        shipmentStatusList = [
          {status: WAIT_RECEIVE, text: getShipmentStatus2Str(WAIT_RECEIVE), num: 0},
          {status: WAIT_SORTING, text: getShipmentStatus2Str(WAIT_SORTING), num: 0},
          {status: FINISHED_SORTING, text: getShipmentStatus2Str(FINISHED_SORTING), num: 0},
          {status: FINISHED_SHELVES, text: getShipmentStatus2Str(FINISHED_SHELVES), num: 0},
          {status: 'all', text: '全部', num: 0}, // 全部
        ]
      }
      shipmentStatusList.forEach(item=>{
        const status = item.status
        const obj = this.tabNumber.find(_item=> _item.status === status)
        if(obj){
          item.num = obj.num
        }
      })

      return shipmentStatusList;
    }
  },
  data(){


    const shipmentTypeList = [
      {type: 'one_shipping', text: this.$t('shipment.oneStock')},
      {type: 'middle', text: '暂存中转'},
      {type: 'mkd_full', text: 'ML直送'},
      {type: 'mkd_cbt_full', text: 'ML直送(CBT)'},
      {type: 'offline_delivery', text: '线下配送'},
    ];
    if(isMiddleRole()){
      const index = shipmentTypeList.findIndex(item=>item.type === 'one_shipping')
      shipmentTypeList.splice(index, 1)
    }
    if(isOneShippingRole()){
      const index = shipmentTypeList.findIndex(item=>item.type === 'middle')
      shipmentTypeList.splice(index, 1)
      const index2 = shipmentTypeList.findIndex(item=>item.type === 'mkd_full')
      shipmentTypeList.splice(index2, 1)
      const index3 = shipmentTypeList.findIndex(item=>item.type === 'mkd_cbt_full')
      shipmentTypeList.splice(index3, 1)
      const index4 = shipmentTypeList.findIndex(item=>item.type === 'offline_delivery')
      shipmentTypeList.splice(index4, 1)
    }
    if(shipmentTypeList.length > 1){
      shipmentTypeList.unshift({type: 'all', text: '全部'})
    }

    return {
      shipmentTypeList,
      queryParams: {
        type: '',
        userIds: [-1],
        page: 1,
        pageSize: 20,
        shipmentType: shipmentTypeList[0].type, // 货件单类型
        labelStatus: '',
        keyword: '',
        transferType: '', // 运输类型
        // status2: shipmentStatusList[0].status, // 货件单状态
        status2: 'all', // 货件单状态
        planType: '',
        BGMethod: '',
      },
      loading: false,
      delLoading: false,
      data: [],
      total: 0,
      tabNumber: [],
    }
  },
  created() {
    // this.getData();
    this.setPlanTypeValue()
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    })
  },
  methods:{
    getShipmentTypeStr2,
    getShipmentBGMethodStr,
    FINISHED_SHELVES() {
      return FINISHED_SHELVES
    },
    isOneShippingRole,
    getShipmentStatus2Str,
    getShipmentStatusStr,
    jumpPageNewTag,
    jumpCombinationInfo,
    getLabelStatusStr,
    getShipmentTypeStr,
    getShopeeName,
    getFalabellaName,
    getMercadoName,
    getWareHouseName,
    setPlanTypeValue(){
      const name = this.$route.name
      const obj = {
        shipmentListFirstLeg: PLAN_TYPE_FL, // 头程
        shipmentListMoveWarehouse: PLAN_TYPE_MW, // 尾程
      }
      this.queryParams.planType = obj[name] ? obj[name] : ''
    },
    getData(){
      this.loading = true
      getShipmentList(this.queryParams)
        .then(res=>{
          this.loading = false
          this.data = res.data
          this.total = res.info.total
          this.tabNumber = res.info.tabNumber
        })
    },
    changeOption(){
      this.queryParams.page = 1;
      this.getData()
    },
    delShipment(row){
      this.$warning(`${this.$t('shipment.delText')}`,{
        title: `${this.$t('shipment.delTitle')}`,
      })
        .then(() => {
          this.delLoading = true
          delShipment(row.id)
            .then(res=>{
              this.delLoading = false
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
                this.$store.dispatch('user/getInfo');
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
    },
    jumpInfo(row){
      this.$router.push({
        name: 'shipmentInfo',
        query: {
          id: row.id,
        }
      })
    },
    canDelShipment(row){
      return row.planStatus === 'ready_to_ship'
    },
    changeShipmentType(){
      this.queryParams.status2 = 'all';
      this.changeOption()
    },
    // 获取左侧货件单的数据
    getRlBoxNum(row){
      let num = 0;
      const status = row.status2;
      const arr1 = [WAIT_CONFIRM, WAIT_FL_RECEIVE]; // 待国内接收
      const arr2 = [WAIT_MAKE_CABINET] // 待装柜
      const arr3 = [WAIT_CUSTOMS_DECLARATION, WAIT_SHIPMENT, WAIT_CUSTOMS_CLEARANCE]; // 运输中的
      const arr4 = [WAIT_RECEIVE]; // 待海外接受
      const arr5 = [WAIT_SORTING]; // 待分拣
      const arr6 = [FINISHED_SORTING]; // 已分拣
      const arr7 = [HALF_SHELVES, FINISHED_SHELVES]; // 部分上架 已上架
      const arr8 = [OFFLINE_DELIVERED, OFFICIAL_DELIVERED, ABOLISHED]; // 线下配送 已送仓 已作废的
      if(arr1.includes(status)){
        // 待国内接收
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.isReceived === 1){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr2.includes(status)){
        // 待装柜
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.containerId){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr3.includes(status)){
        // 运输中的
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.status === 'received'){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr4.includes(status)){
        // 待海外接受的
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.status === 'wait_sorting'){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr5.includes(status)){
        // 待分拣
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.status === 'sorted'){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr6.includes(status)){
        // 已分拣
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.status === 'sorted'){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr7.includes(status)){
        // 已上架的
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(item.status === 'listed'){
            set.add(item.boxId)
          }
        })
        num = set.size
      }else if(arr8.includes(status)){
        //  线下配送 已送仓 已作废的
        const set = new Set();
        row.boxLabelList.forEach(item=>{
          if(!item.isReceiveExcept && !item.isSortingExcept){
            set.add(item.boxId)
          }
        })
        num = set.size

      }

      return num;
    }
  },
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .shipment-type-box{
    padding-bottom: 10px;
    border-bottom: 1px solid #cccccc;
    margin-bottom: 10px;
  }
}
.platform-select{
  width: 215px;
}
.batch-box{
  position: relative;
  width: 400px;
  .batch-btn{
    position: absolute;
    bottom: 10px;
    right: 5px;
  }
}
</style>
